package com.masterclient.app.modules.goods.adapter

import android.app.Activity
import android.os.Build
import android.os.Environment
import android.support.v4.view.PagerAdapter
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.aliyun.vodplayer.media.AliyunLocalSource.AliyunLocalSourceBuilder
import com.aliyun.vodplayer.media.IAliyunVodPlayer
import com.aliyun.vodplayerview.widget.AliyunVodPlayerView
import com.masterclient.app.App
import com.masterclient.app.R
import java.lang.ref.WeakReference


/**
 * 作者：sean
 * 创建时间：2018/5/29 15:43
 * 功能说明：
 */
class GoodsImageAdapter(product_id:String,product_name:String,images: List<String>, context: Activity,videoStr:String?,mOnClickViewListener:OnClickViewListener) : PagerAdapter() {


    private val product_id = product_id
    private val product_name = product_name
    private val mImages = images
    private val activity = context
    private val video = videoStr
    private val onClickViewListener = mOnClickViewListener;
    var mAliyunVodPlayerView:AliyunVodPlayerView? = null
    var iv_img:ImageView? = null
    var iv_bofang:ImageView? = null

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        if(position == 0&&!TextUtils.isEmpty(video)){
            val view  = View.inflate(activity, R.layout.goods_video_pager,null)
            mAliyunVodPlayerView = view.findViewById(R.id.video_view) as AliyunVodPlayerView
            iv_img = view.findViewById(R.id.iv_image) as ImageView
            iv_bofang = view.findViewById(R.id.iv_bofang) as ImageView

            if(!TextUtils.isEmpty(mImages[position])){
                App.picasso.load(mImages[position]).into(iv_img)
            }
            mAliyunVodPlayerView!!.keepScreenOn = true//保持屏幕敞亮

            val sdDir = Environment.getExternalStorageDirectory().absolutePath + "/test_save_cache"
            mAliyunVodPlayerView!!.setPlayingCache(true, sdDir, 60 * 60 /*时长, s */, 300 /*大小，MB*/)
            mAliyunVodPlayerView!!.setTheme(AliyunVodPlayerView.Theme.Orange)
//            mAliyunVodPlayerView.setCirclePlay(true)

            val alsb = AliyunLocalSourceBuilder()
            alsb.setSource(video)
            val localSource = alsb.build()
            mAliyunVodPlayerView!!.setLocalSource(localSource)
//            mAliyunVodPlayerView.setOnPreparedListener(MyPrepareListener(activity))
//            mAliyunVodPlayerView.setOnFirstFrameStartListener(MyFrameInfoListener(this))
//            mAliyunVodPlayerView.setOnChangeQualityListener(MyChangeQualityListener(this))
//            mAliyunVodPlayerView.setOnStoppedListner(MyStoppedListener(this))
            mAliyunVodPlayerView!!.enableNativeLog()

            mAliyunVodPlayerView!!.setTitleBarCanShow(false)
            mAliyunVodPlayerView!!.lockScreen(true)



            mAliyunVodPlayerView?.setOnAutoPlayListener(IAliyunVodPlayer.OnAutoPlayListener {  })
            mAliyunVodPlayerView!!.setOnPreparedListener {
                iv_bofang?.visibility = View.VISIBLE
            }
            mAliyunVodPlayerView!!.setOnCompletionListener {
                iv_bofang?.visibility = View.VISIBLE
                iv_img?.visibility = View.VISIBLE
            }
//            mAliyunVodPlayerView.set
            iv_bofang?.setOnClickListener{
                if(iv_bofang?.tag == true){
                    mAliyunVodPlayerView!!.rePlay()
                }else{
                    mAliyunVodPlayerView!!.start()
                    iv_bofang?.tag = true
                }
                iv_bofang?.visibility = View.GONE
                iv_img?.visibility = View.GONE
            }
            container.addView(view)
            return view

        }else{
            if(mAliyunVodPlayerView?.isPlaying == true){
                mAliyunVodPlayerView?.pause()
                iv_bofang?.visibility = View.VISIBLE
                iv_img?.visibility = View.VISIBLE
            }
            var index :Int = position
            if(!TextUtils.isEmpty(video)){
                index = position - 1;
            }
            val imageView = ImageView(activity)
            val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
            imageView.layoutParams = params
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            imageView.setOnClickListener(View.OnClickListener {
                onClickViewListener.getPosition(index)
            })
            if(!TextUtils.isEmpty(mImages[index])){
                App.picasso.load(mImages[index]).into(imageView)
            }
            container.addView(imageView)
            return imageView
        }
    }

    public fun destroy(){
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView?.onDestroy()
        }
    }

    override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
        container.removeView(`object` as View)
    }

    override fun isViewFromObject(view: View, `object`: Any): Boolean {
        return view === `object`
    }

    override fun getCount(): Int {
        if(TextUtils.isEmpty(video)){
            return mImages.size
        }else{
            return mImages.size + 1
        }
    }

    interface OnClickViewListener{
        fun getPosition(position: Int)
    }


    private class MyPrepareListener(skinActivity: Activity) : IAliyunVodPlayer.OnPreparedListener {

        private val activityWeakReference: WeakReference<Activity>

        init {
            activityWeakReference = WeakReference(skinActivity)
        }

        override fun onPrepared() {
            val activity = activityWeakReference.get()
            onPrepared()
        }
    }

    private fun onPrepared() {
        //        logStrs.add(format.format(new Date()) + getString(R.string.log_prepare_success));
        //        Toast.makeText(SkinActivity.this.getApplicationContext(), R.string.toast_prepare_success, Toast.LENGTH_SHORT).show();
    }

    private fun onCompletion() {
        //        logStrs.add(format.format(new Date()) + getString(R.string.log_play_completion));
        //        Toast.makeText(SkinActivity.this.getApplicationContext(), R.string.toast_play_compleion, Toast.LENGTH_SHORT).show();

    }

    private class MyFrameInfoListener(skinActivity: Activity) : IAliyunVodPlayer.OnFirstFrameStartListener {

        private val activityWeakReference: WeakReference<Activity>

        init {
            activityWeakReference = WeakReference(skinActivity)
        }

        override fun onFirstFrameStart() {

            val activity = activityWeakReference.get()
            onFirstFrameStart()
        }
    }

    private fun onFirstFrameStart() {
        val debugInfo = mAliyunVodPlayerView!!.getAllDebugInfo()
        var createPts: Long = 0
        if (debugInfo.get("create_player") != null) {
            val time = debugInfo.get("create_player")
            createPts = java.lang.Double.parseDouble(time).toLong()
            //            logStrs.add(format.format(new Date(createPts)) + getString(R.string.log_player_create_success));
        }
        if (debugInfo.get("open-url") != null) {
            val time = debugInfo.get("open-url")
            val openPts = java.lang.Double.parseDouble(time).toLong() + createPts
            //            logStrs.add(format.format(new Date(openPts)) + getString(R.string.log_open_url_success));
        }
        if (debugInfo.get("find-stream") != null) {
            val time = debugInfo.get("find-stream")
            val findPts = java.lang.Double.parseDouble(time).toLong() + createPts
            //            logStrs.add(format.format(new Date(findPts)) + getString(R.string.log_request_stream_success));
        }
        if (debugInfo.get("open-stream") != null) {
            val time = debugInfo.get("open-stream")
            val openPts = java.lang.Double.parseDouble(time).toLong() + createPts
            //            logStrs.add(format.format(new Date(openPts)) + getString(R.string.log_start_open_stream));
        }
        //        logStrs.add(format.format(new Date()) + getString(R.string.log_first_frame_played));
    }


    private class MyChangeQualityListener(skinActivity: Activity) : IAliyunVodPlayer.OnChangeQualityListener {

        private val activityWeakReference: WeakReference<Activity>

        init {
            activityWeakReference = WeakReference(skinActivity)
        }

        override fun onChangeQualitySuccess(finalQuality: String) {

            val activity = activityWeakReference.get()
            onChangeQualitySuccess(finalQuality)
        }

        override fun onChangeQualityFail(code: Int, msg: String) {
            val activity = activityWeakReference.get()
            onChangeQualityFail(code, msg)
        }
    }

    private fun onChangeQualitySuccess(finalQuality: String) {
        //        logStrs.add(format.format(new Date()) + getString(R.string.log_change_quality_success));
        //        Toast.makeText(SkinActivity.this.getApplicationContext(), getString(R.string.log_change_quality_success), Toast.LENGTH_SHORT).show();
    }

    internal fun onChangeQualityFail(code: Int, msg: String) {
        //        logStrs.add(format.format(new Date()) + getString(R.string.log_change_quality_fail) + " : " + msg);
        //        Toast.makeText(SkinActivity.this.getApplicationContext(), getString(R.string.log_change_quality_fail), Toast.LENGTH_SHORT).show();
    }

    private class MyStoppedListener(skinActivity: Activity) : IAliyunVodPlayer.OnStoppedListener {

        private val activityWeakReference: WeakReference<Activity>

        init {
            activityWeakReference = WeakReference(skinActivity)
        }

        override fun onStopped() {

            val activity = activityWeakReference.get()
            onStopped()
        }
    }
    private fun isStrangePhone(): Boolean {
        val strangePhone = (Build.DEVICE.equals("mx5", ignoreCase = true)
                || Build.DEVICE.equals("Redmi Note2", ignoreCase = true)
                || Build.DEVICE.equals("Z00A_1", ignoreCase = true)
                || Build.DEVICE.equals("hwH60-L02", ignoreCase = true)
                || Build.DEVICE.equals("hermes", ignoreCase = true)
                || Build.DEVICE.equals("V4", ignoreCase = true) && Build.MANUFACTURER.equals("Meitu", ignoreCase = true))
        return strangePhone

    }


}